<template>
    <el-affix  :offset="85">
      <!-- 通用的header -->
      <ReviewJudgeCommonHeader
        v-if="awardsInfo.awardsType === 0"
        @open-rule="handleOpenRules"
        @open-confirm="handleOpenConfirm"
      />
      <!-- 师昌绪header -->
      <ReviewJudgeScxHeader
        v-if="awardsInfo.awardsType === 1"
        @open-rule="handleOpenRules"
        @open-confirm="handleOpenConfirm"
      />
    </el-affix>

  <!-- 表格 -->
  <ReviewJudgeTable ref="reviewJudgeTableRef" v-if="awardsId && currentStage && currentRound" />

  <!-- 评审规则 -->
  <JudgeRules ref="judgeRulesRef" />
  <!-- 推荐名单确认弹窗 -->
  <ReviewJudgeResultForm ref="reviewJudgeResultFormRef" />
</template>

<script setup lang="ts">
/** 评选现场 列表 */
import { storeToRefs } from 'pinia'
import { useInstanceReviewSceneStore } from '@/store/modules/instance/instanceReivewScene'
import ReviewJudgeTable from '@/views/awards/instanceReview/ReviewJudgeTable.vue'
import JudgeRules from '@/views/awards/instanceReview/JudgeRules.vue'
import ReviewJudgeResultForm from '@/views/awards/instanceReview/ReviewJudgeResultForm.vue'
import ReviewJudgeScxHeader from '@/views/awards/instanceReview/ReviewJudgeScxHeader.vue'
import ReviewJudgeCommonHeader from '@/views/awards/instanceReview/ReviewJudgeCommonHeader.vue'
import { type RouteLocationNormalizedLoaded, useRouter } from 'vue-router'
import { nextTick, ref, unref } from 'vue'
import { useTagsViewStore } from '@/store/modules/tagsView'
import { JudgesSceneCheckVO, ReviewSceneApi } from '@/api/awards/reviewscene'

defineOptions({ name: 'ReviewJudgeScene' })

const route = useRoute()
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const { currentRoute, push, replace } = useRouter()
const tagsViewStore = useTagsViewStore()

const instanceReviewSceneStore = useInstanceReviewSceneStore()
const { awardsId, awardsInfo, currentStage, currentRound } = storeToRefs(instanceReviewSceneStore)

const loading = ref(false)
const reviewJudgeTableRef = ref<InstanceType<typeof ReviewJudgeTable>>()
const judgeRulesRef = ref<InstanceType<typeof JudgeRules>>()

watch(currentRound, (newVal, oldVal) => {
  // 除了scx初评，其他情况都可能有下一轮
  if (awardsInfo.value.awardsType === 1 && currentStage.value?.name === '初评') return
  // 如果终评轮次发生变化，弹窗提示开启新一轮
  if (newVal && oldVal && newVal.roundId !== oldVal.roundId) {
    instanceReviewSceneStore.getAwardsInfo()
    openNewRoundVote()
  }
})

watch(
  () => currentRound.value?.isJudgesConfirm,
  (newVal, oldVal) => {
    // 如果管理端开启了终评结果确认，弹窗提示
    if (currentStage.value?.name === '终评' && oldVal === false && newVal) {
      finalResultConfirmTip()
    }
  }
)

const selectedTag = ref<RouteLocationNormalizedLoaded>()
// 提示开启新一轮
const openNewRoundVote = () => {
  ElMessageBox.alert(
    t('reviewJudgeScene.message.newRound', { text: currentRound.value?.name }),
    t('common.confirmTitle'),
    {
      confirmButtonText: t('common.ok'),
      type: 'warning',
      showClose: false,
      showCancelButton: false,
      closeOnClickModal: false
    }
  ).then(async () => {
    // 更新表格数据
    reviewJudgeTableRef.value?.resetQuery()
    selectedTag.value = unref(currentRoute)
    tagsViewStore.delCachedView()
    const { path, query } = selectedTag.value
    await nextTick()
    replace({
      path: '/redirect' + path,
      query: query
    })
  })
}

// 提示终评结果确认
const finalResultConfirmTip = async () => {
  ElMessageBox.alert(t('reviewJudgeScene.message.finalResultConfirm'), t('common.confirmTitle'), {
    confirmButtonText: t('common.view'),
    cancelButtonText: t('common.cancel'),
    type: 'warning',
    showClose: false,
    showCancelButton: true,
    closeOnClickModal: false
  }).then(() => {
    handleOpenConfirm()
  })
}

// 获取通用当前阶段规则
const getCommonCurrentStageRules = () => {
  const rules = awardsInfo.value?.instanceRules || []
  return (
    rules.find(
      (item) =>
        (item.judgeStage === '1' && currentStage.value?.name === '初评') ||
        (item.judgeStage === '2' && currentStage.value?.name === '终评')
    )?.judgeRule || ''
  )
}

// 获取scx当前阶段规则
const getScxCurrentStageRules = () => {
  const { initialRules, finalRules } = awardsInfo.value || {}
  const stageName = currentStage.value?.name

  if (!initialRules && !finalRules) return ''

  return stageName === '初评' ? initialRules || '' : stageName === '终评' ? finalRules || '' : ''
}

// 查看评审规则
const handleOpenRules = () => {
  if (!awardsInfo.value) {
    return
  }
  let content = ''
  if (awardsInfo.value.awardsType === 0) {
    content = getCommonCurrentStageRules()
  } else if (awardsInfo.value.awardsType === 1) {
    content = getScxCurrentStageRules()
  }
  judgeRulesRef.value?.open(content)
}

// 打开推荐名单确认弹窗
const reviewJudgeResultFormRef = ref<InstanceType<typeof ReviewJudgeResultForm>>()
const handleOpenConfirm = () => {
  if (!currentRound.value) {
    return
  }
  reviewJudgeResultFormRef.value?.open()
}

// 轮询当前阶段
let resultConfirmInterval: NodeJS.Timeout | null = null
// 开启轮询
const startPolling = () => {
  resultConfirmInterval = setInterval(instanceReviewSceneStore.getCurrentStageRound, 30000)
}
// 停止轮询
const stopPolling = () => {
  if (resultConfirmInterval) {
    clearInterval(resultConfirmInterval)
    resultConfirmInterval = null
  }
}

// 查询信息
const getInfo = async () => {
  loading.value = true
  await instanceReviewSceneStore.getCurrentStageRound()
  if (currentStage.value) {
    // 查询评奖基本信息
    await instanceReviewSceneStore.getAwardsInfo()
    // 查询是否终评结果已确认
    await instanceReviewSceneStore.getFinalResultConfirmed()
    // nextTick(() => {
    //   handleOpenRules()
    // }).then() //暂时去除进来就弹规则确认
  }
  // 如果当前阶段是终评，开启轮询
  if (currentStage.value?.name === '终评') {
    startPolling()
  }
  loading.value = false
}

/** 初始化 **/
onMounted(async () => {
  if (!route.params.instanceId) {
    await push('/awards/instance-review')
    return
  }
  const instanceId = route.params.instanceId as string

  // 进来了也得校验
  const result: JudgesSceneCheckVO = await ReviewSceneApi.checkJudgesSceneAvailable(instanceId)
  if (!result.isAvailable) {
    message.error(result.reason)
    await push('/awards/instance-review')
    return
  }

  instanceReviewSceneStore.setAwardsId(instanceId)
  // 查询评审进行信息
  await getInfo()
})

onUnmounted(() => {
  stopPolling()
  instanceReviewSceneStore.reset()
})
</script>

<style lang="scss" scoped>
:deep(.el-descriptions__body .el-descriptions__table .el-descriptions__cell) {
  font-size: 13px;
  line-height: 18px;
}

:deep(.vxe-cell .el-button + .el-button) {
  margin-left: 0;
}
</style>
